package com.gotrade.springbootexceptiondemo.service.impl;

import com.gotrade.springbootexceptiondemo.common.enums.ResultCode;
import com.gotrade.springbootexceptiondemo.exception.ApiException;
import com.gotrade.springbootexceptiondemo.model.User;
import com.gotrade.springbootexceptiondemo.service.UserService;
import io.swagger.annotations.Api;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import java.time.LocalDate;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author jason.tang
 * @create 2019/4/28
 * @description
 */

@Service("userService")
public class UserServiceImpl implements UserService {
    private static List<User> userList = null;

    @PostConstruct
    private void autoStartup() {
        userList = new ArrayList<>();
        userList.add(User.builder().userNum(1).username("jason").birthday(LocalDate.now()).build());
        userList.add(User.builder().userNum(2).username("lily").birthday(LocalDate.now()).build());
        userList.add(User.builder().userNum(3).username("tom").birthday(LocalDate.now()).build());
    }


    @Override
    public User getUserByNum(Integer userNum) {
        User user = userList.stream()
                .filter(u -> Objects.equals(userNum, u.getUserNum()))
                .findFirst()
                .orElse(null);
        if (user == null) {
            throw new ApiException(ResultCode.USER_DOES_NOT_EXIST);
        }
        return user;
    }

    @Override
    public User addUser(User user) {
        boolean noneMatch = userList.stream()
                .noneMatch(u -> Objects.equals(u.getUsername(), user.getUsername()));
        if (!noneMatch) {
            throw new ApiException(ResultCode.USER_ALREADY_EXIST, user.getUsername());
        }
        user.setUserNum(userList.size() + 1);
        userList.add(user);
        return user;
    }


}
